import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { saveAs } from 'file-saver'
import { getAuthenticationHeader } from '@/utils/store'
import { blobValidate } from '@/utils/validate'

let downloadLoadingInstance
export default {
  browse(url, method) {
    return new Promise((resolve, reject) => {
      axios({
        method: method,
        url: url,
        responseType: 'blob',
        headers: getAuthenticationHeader()
      }).then(async (response) => {
        let blob = new Blob([response.data], {type : 'text/html'})
        resolve(window.URL.createObjectURL(blob))
      }).catch((error) => {
        Message.error('数据加载错误！')
        reject(error)
      })
    })
  },
  download(url) {
    downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: getAuthenticationHeader()
    }).then(async (response) => {
      const isLogin = await blobValidate(response.data)
      if (isLogin) {
        const blob = new Blob([response.data], { type: 'application/octet-stream' })
        this.saveAs(blob, decodeURI(response.headers['download-filename']))
      } else {
        Message.error('下载文件出现错误，请联系管理员！')
      }
      downloadLoadingInstance.close()
    }).catch((r) => {
      Message.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
  },
  downloadById(fileId) {
    this.download(process.env.VUE_APP_URL_PREFIX + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download/${fileId}`)
  },
  saveAs(text, name, opts) {
    saveAs(text, name, opts)
  }
}
